import api from '../../api/index'
import common from "../../common/index";
import envConfig from '../../env'
const app = getApp()
Component({
  data: {
    hasUserInfo: false,
    statusBarHeight: app.globalData.statusBarHeight,
    navBarHeight: app.globalData.navBarHeight,
    pcenterPageShow: false,
    summaryPageShow: false,
    uid: '',
    selectedButton: 'free', // 默认选中自由主题写作
    inputText: '', // 输入文本内容
    selectedSearchTypes: {
      aispire: true,
      thinktank: false,
      web: false
    },
    selectedLanguage: '中文', // 默认选中中文
    selectedWordCount: '2000-6000字', // 默认选中字数范围
    selectedOutline: '一级大纲', // 默认选中大纲层级
    showLanguageSheet: false,
    showWordCountSheet: false,
    showOutlineSheet: false,
    selectedFolderName: '', // 选中的文件夹名称
    selectDirShow: false, // 文件夹选择弹窗显示状态
    dirList: [], // 文件夹列表
    fieldNames: {
      text: 'dir_name',
      value: 'dir_id',
      children: 'children',
    },
    cacheSelectedDir: null, // 缓存的选中文件夹
    languageActions: [
      { name: '中文', value: 'zh' },
      { name: '英文', value: 'en' }
    ],
    wordCountActions: [
      { name: '2000-6000字', value: '2000-6000字' },
      { name: '6000-10000字', value: '6000-10000字' },
      { name: '10000-200000字', value: '10000-200000字' },
      { name: '200000字以上', value: '200000字以上' }
    ],
    outlineActions: [
      { name: '一级大纲', value: '一级大纲' },
      { name: '二级大纲', value: '二级大纲' }
    ],
  },
  lifetimes: {
    ready() {
      const user = common.getAppUserInfo()
      this.data.uid = user.uid
      this.setData({
        uid: user.uid
      })
    }
  },
  pageLifetimes: {

  },
  methods: {
    showPcenterPage() {
      this.setData({
        pcenterPageShow: true
      })
    },
    closePcenterPage() {
      this.setData({
        pcenterPageShow: false
      })
    },
    
    // 返回上一页
    handleGoBack() {
      wx.navigateBack()
    },
    
    // 选择写作类型
    selectWritingType(e) {
      const type = e.currentTarget.dataset.type
      this.setData({
        selectedButton: type
      })
    },
    
    // 切换搜索类型（支持多选）
    toggleSearchType(e) {
      const type = e.currentTarget.dataset.type
      const currentState = this.data.selectedSearchTypes[type]
      
      this.setData({
        [`selectedSearchTypes.${type}`]: !currentState
      })
    },
    
    // 显示语言选择弹窗
    showLanguageSheet() {
      this.setData({
        showLanguageSheet: true
      })
    },
    
    // 关闭语言选择弹窗
    closeLanguageSheet() {
      this.setData({
        showLanguageSheet: false
      })
    },
    
    // 选择语言
    selectLanguage(e) {
      const value = e.detail.value || e.currentTarget.dataset.value
      this.setData({
        selectedLanguage: value,
        showLanguageSheet: false
      })
    },
    
    // 显示字数选择弹窗
    showWordCountSheet() {
      this.setData({
        showWordCountSheet: true
      })
    },
    
    // 关闭字数选择弹窗
    closeWordCountSheet() {
      this.setData({
        showWordCountSheet: false
      })
    },
    
    // 选择字数
    selectWordCount(e) {
      const value = e.detail.value || e.currentTarget.dataset.value
      
      // 根据字数选择更新大纲层级选项
      let outlineOptions = []
      let defaultOutline = ''
      
      switch(value) {
        case '2000-6000字':
          outlineOptions = [
            { name: '一级大纲', value: '一级大纲' },
            { name: '二级大纲', value: '二级大纲' }
          ]
          defaultOutline = '一级大纲'
          break
        case '6000-10000字':
          outlineOptions = [
            { name: '一级大纲', value: '一级大纲' },
            { name: '二级大纲', value: '二级大纲' },
            { name: '三级大纲', value: '三级大纲' }
          ]
          defaultOutline = '一级大纲'
          break
        case '10000-200000字':
          outlineOptions = [
            { name: '二级大纲', value: '二级大纲' },
            { name: '三级大纲', value: '三级大纲' },
            { name: '四级大纲', value: '四级大纲' }
          ]
          defaultOutline = '二级大纲'
          break
        case '200000字以上':
          outlineOptions = [
            { name: '三级大纲', value: '三级大纲' },
            { name: '四级大纲', value: '四级大纲' }
          ]
          defaultOutline = '三级大纲'
          break
      }
      
      this.setData({
        selectedWordCount: value,
        selectedOutline: defaultOutline,
        outlineActions: outlineOptions,
        showWordCountSheet: false
      })
    },
    
    // 显示大纲层级选择弹窗
    showOutlineSheet() {
      this.setData({
        showOutlineSheet: true
      })
    },
    
    // 关闭大纲层级选择弹窗
    closeOutlineSheet() {
      this.setData({
        showOutlineSheet: false
      })
    },
    
    // 选择大纲层级
    selectOutline(e) {
      const value = e.detail.value || e.currentTarget.dataset.value
      this.setData({
        selectedOutline: value,
        showOutlineSheet: false
      })
    },
    
    // 选择文件夹
    selectFolder() {
      this.setData({
        selectDirShow: true
      });
      this.getDirList();
    },
    
    // 获取文件夹列表
    async getDirList() {
      try {
        const res = await api.getDirFileList({
          uid: parseInt(this.data.uid),
          dir_id: ''
        });
        if (res.directories && res.directories.length) {
          const dirList = [{dir_id: '', dir_name: '全部目录'}].concat(res.directories);
          this.setData({ dirList });
        }
      } catch (error) {
        console.error('获取文件夹列表失败:', error);
      }
    },
    
    // 文件夹选择变化
    handleSelectDirChange(e) {
      const selectItem = e.detail.selectedOptions[e.detail.selectedOptions.length-1];
      this.data.cacheSelectedDir = selectItem;
    },
    
    // 关闭文件夹选择弹窗
    handleSelectDirClose() {
      this.setData({
        selectDirShow: false
      });
    },
    
    // 确认选择文件夹
    handleSelectDirConfirm() {
      if (this.data.cacheSelectedDir) {
        this.setData({
          selectedFolderName: this.data.cacheSelectedDir.dir_name,
          selectDirShow: false
        });
      }
    },
    
    // 生成大纲
    async generateOutline() {
      if (!this.data.inputText.trim()) {
        wx.showToast({
          title: '请输入论文主题',
          icon: 'none'
        });
        return;
      }

      wx.showLoading({
        title: '生成大纲中...'
      });

      try {
        const uid = parseInt(this.data.uid);
        const language = this.data.selectedLanguage === '中文' ? 'zh' : 'en';
        const level = this.getOutlineLevel();
        const type = this.getWordCountType();
        
        let apiCall;
        let requestData;

        switch(this.data.selectedButton) {
          case 'free':
            // 自由主题写作
            requestData = {
              uid,
              category: 'freedom',
              idea: this.data.inputText,
              knowledge_base: this.getKnowledgeBase(),
              type,
              level,
              language
            };
            apiCall = api.generateWritingOutline(requestData);
            break;
            
          case 'review':
            // 文献综述
            if (!this.data.selectedFolderName) {
              wx.hideLoading();
              wx.showToast({
                title: '请选择文件夹',
                icon: 'none'
              });
              return;
            }
            requestData = {
              uid,
              category: 'literature',
              idea: this.data.inputText,
              dir_id: this.data.cacheSelectedDir?.dir_id || '',
              type,
              style: 'timeline',
              level,
              language
            };
            apiCall = api.generateLiteratureReviewOutline(requestData);
            break;
            
          case 'academic':
            // 学术写作
            requestData = {
              uid,
              category: 'paper',
              idea: this.data.inputText,
              knowledge_base: this.getKnowledgeBase(),
              type,
              level,
              language
            };
            apiCall = api.generateAcademicOutline(requestData);
            break;
        }

        // 跳转到大纲展示页面
        const writingTypeMap = {
          'free': '自由主题写作',
          'review': '文献综述',
          'academic': '学术写作'
        };
        
        const languageMap = {
          'zh': '中文',
          'en': '英文'
        };
        
        const levelMap = {
          1: '一级大纲',
          2: '二级大纲',
          3: '三级大纲',
          4: '四级大纲'
        };
        
        wx.hideLoading();
        
        // 跳转到大纲展示页面
        wx.navigateTo({
          url: `/pages/outline-display/outline-display?` +
               `idea=${encodeURIComponent(this.data.inputText)}&` +
               `writingType=${encodeURIComponent(writingTypeMap[this.data.selectedButton])}&` +
               `wordCount=${encodeURIComponent(this.data.selectedWordCount)}&` +
               `outlineLevel=${encodeURIComponent(levelMap[level])}&` +
               `language=${encodeURIComponent(languageMap[language])}&` +
               `requestData=${encodeURIComponent(JSON.stringify(requestData))}`
        });
      } catch (error) {
        wx.hideLoading();
        wx.showToast({
          title: '生成大纲失败',
          icon: 'error'
        });
        console.error('生成大纲错误:', error);
      }
    },

    // 获取大纲层级数字
    getOutlineLevel() {
      const levelMap = {
        '一级大纲': 1,
        '二级大纲': 2,
        '三级大纲': 3,
        '四级大纲': 4
      };
      return levelMap[this.data.selectedOutline] || 1;
    },

    // 获取字数类型
    getWordCountType() {
      const typeMap = {
        '2000-6000字': 'short',
        '6000-10000字': 'medium',
        '10000-200000字': 'long',
        '200000字以上': 'very_long'
      };
      return typeMap[this.data.selectedWordCount] || 'short';
    },

    // 获取知识库
    getKnowledgeBase() {
      const knowledgeBase = [];
      if (this.data.selectedSearchTypes.aispire) {
        knowledgeBase.push('aispire_knowledge_base');
      }
      if (this.data.selectedSearchTypes.thinktank) {
        knowledgeBase.push('private_knowledge_base');
      }
      if (this.data.selectedSearchTypes.web) {
        knowledgeBase.push('online_search');
      }
      return knowledgeBase;
    },
    
     // 处理文本输入
  onInput: function(e) {
    this.setData({
      inputText: e.detail.value
    });
  },
    
    
}
})
